package com.ztom.v2;

import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * @author ZhangTao
 */
public class Code34MergeKSortedLists {

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) {
            return null;
        }
        if (lists.length == 1) {
            return lists[0];
        }

        PriorityQueue<ListNode> priorityQueue = new PriorityQueue<>(Comparator.comparingInt(a -> a.val));
        for (ListNode list : lists) {
            if (list != null) {
                priorityQueue.add(list);
            }
        }

        ListNode dummy = new ListNode(-1);
        ListNode node = dummy;
        ListNode cur;
        while (!priorityQueue.isEmpty()) {
            cur = priorityQueue.poll();
            node.next = cur;
            node = node.next;
            if (cur.next != null) {
                priorityQueue.add(cur.next);
            }
        }
        return dummy.next;
    }
}
